//
//  SQLaunchView.swift
//  SwiftWeibo
//
//  Created by 苏强 on 16/12/2.
//  Copyright © 2016年 suqianghotel. All rights reserved.
//

import UIKit

class SQLaunchView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
  
    @IBOutlet weak var enterWeibo: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    class func launchView()->SQLaunchView
    {
        let nib = UINib(nibName: "SQLaunchView", bundle: nil)
        
        let view =  nib.instantiate(withOwner: nil, options: nil)[0] as! SQLaunchView
        
        view.frame = UIScreen.main.bounds
        
        
        return view
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.backgroundColor = UIColor.clear
        
        self.enterWeibo.isHidden = true
        self.enterWeibo.addTarget(self, action: #selector(SQLaunchView.enter), for: .touchUpInside)
        
        self.scrollView.isPagingEnabled = true
        self.scrollView.showsVerticalScrollIndicator = false
        self.scrollView.showsHorizontalScrollIndicator = false
        self.scrollView.bounces = false
        self.scrollView.delegate = self
        
        let count = 4
        let rect = UIScreen.main.bounds
    
        
        for i in 0..<count {
            let imageView = UIImageView(image: UIImage(named:"new_feature_\(i+1)"))
            
            imageView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            self.scrollView.addSubview(imageView)
        }
        
        self.scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
    }
    
    @objc private func enter()
    {
        removeFromSuperview()
    }
    

}


/// MARK: UIScrollViewDelegate
extension SQLaunchView : UIScrollViewDelegate
{
    func scrollViewDidScroll(_ scrollView: UIScrollView) // any offset changes
    {
        
        let page =  Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        self.pageControl.currentPage = page
        self.enterWeibo.isHidden = page != scrollView.subviews.count - 1
        self.pageControl.isHidden = page == scrollView.subviews.count
        
    }
    
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
    {
        // 1. 滚动到最后一屏，让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 2. 判断是否最后一页
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
        
        // 3. 如果是倒数第2页，显示按钮
        enterWeibo.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    
}
